﻿using System;
using System.Linq;
using DAL.Abstract;
using Model;

namespace DAL.Repositories
{
    public class SecurityHelper : ISecurityHelper, IDisposable
    {
        private readonly string adminRoleName = "Administrator";
        private readonly string entryUserRoleName = "Uzytkownik";

        private readonly GenericContext _context;

        public SecurityHelper()
        {
            _context = new GenericContext(); ;
        }

        public SecurityHelper(GenericContext context)
        {
            _context = context;
        }

        private int ConvertUserLoginToUserId(string userLogin)
        {
            var firstOrDefault = _context.USERS
                .FirstOrDefault(i => i.APPLICATIONLOGIN == userLogin);
            return firstOrDefault != null ? firstOrDefault.USERID : 0;
        }

        public bool CheckIfUserIsAdmin(string userLogin)
        {
            try
            {
                var userId = ConvertUserLoginToUserId(userLogin);
                //tutaj dolozyc cache                 
                if (userId == 0)
                    return false;
                var result = (from u in _context.USERS
                              join ur in _context.USERSINROLES on u.USERID equals ur.USERID
                              join uinr in _context.USERSINROLES on ur.ROLEID equals uinr.ROLEID
                              join r in _context.ROLES on ur.ROLEID equals r.ROLEID
                              where u.USERID == userId && r.ROLENAME == adminRoleName
                              select u.USERID);
                return result.Any();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private bool disposed;

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    _context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}
